﻿using System;
using System.Linq;
using System.Text;
using Dapper;
using Dapper.Contrib.Extensions;
namespace Topro.Application.Impl
{
    using Topro.Application.Interface;
    using Topro.Db;
    using Topro.Entity;
    using Topro.Entity.Query;
    using Topro.Entity.Request.Container;
    using Topro.Entity.Response.Container;
    using Topro.Entity.Tables;
    using Topro.Log;

    /// <summary>
    /// 容器业务接口实现
    /// </summary>
    public class ContainerServiceImpl: ContainerService
    {
        #region 注入
        /// <summary>
        /// db
        /// </summary>
        private readonly IDb _db;

        /// <summary>
        /// loggerService
        /// </summary>
        private readonly LoggerService _loggerService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="dapperFactory"></param>
        /// <param name="logger"></param>
        public ContainerServiceImpl(IDb db, LoggerService loggerService)
        {
            _db = db;
            _loggerService = loggerService;
        }
        #endregion

        /// <summary>
        /// 获取容器
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns></returns>
        public ContainerResponse Get(int? id)
        {
            var product = new ContainerResponse();
            if (id.HasValue)
            {
                product = _db.DbConnection.QueryFirst<ContainerResponse>("select * from t_containers where Id=@Id", new { Id = id });
            }
            return product;
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <returns></returns>
        public JResult UpdateStatus(int id, int status)
        {
            var response = new JResult()
            {
                Success = false
            };

            try
            {
                var user = _db.DbConnection.QueryFirst<Containers>("select * from t_containers where Id=@Id", new { Id = id });
                if (user == null)
                {
                    throw new Exception("物料记录不存在.");
                }

                var updateSql = "UPDATE t_containers SET Status=@Status WHERE Id=@Id";

                int result = _db.DbConnection.Execute(updateSql, new { Status = status, Id = id });
                if (result <= 0)
                {
                    throw new Exception("更新失败");
                }
                response.Success = true;
                response.Message = "操作成功.";
            }
            catch (Exception ex)
            {
                response.Message = ex.Message;
            }

            return response;
        }

        /// <summary>
        /// 保存、修改
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public JResult SaveContainer(ContainerSaveRequest request)
        {
            var response = new JResult()
            {
                Success = false
            };

            if (request.Id > 0)
            {
                var containerNameExist = _db.DbConnection.Query<Containers>("SELECT * FROM t_containers WHERE Code=@Code And Id!=@Id", new { Code = request.Code,Id = request.Id });
                if (containerNameExist != null && containerNameExist.Any())
                {
                    throw new Exception("容器已存在.");
                }

                var container = _db.DbConnection.QueryFirst<Containers>("select * from t_containers where Id=@Id", new { Id = request.Id });
                if (container == null)
                {
                    throw new Exception("容器记录不存在.");
                }

                container.Code = request.Code;
                container.Status = request.Status.Value;
                container.Remark = request.Remark;
                container.DisplayOrder = int.Parse(request.DisplayOrder);
                container.CreatedBy = request.CreatedBy;
                container.CreateTime = DateTime.Now;

                //更新
                _db.DbConnection.Update<Containers>(container);
                //
                response.Success = true;
            }
            else
            {
                var permissionNameExist = _db.DbConnection.Query<Containers>("SELECT * FROM t_containers WHERE Id=@Id", new { Id = request.Id });
                if (permissionNameExist != null && permissionNameExist.Any())
                {
                    throw new Exception("容器已存在.");
                }

                var container = new Containers()
                {
                    Code = request.Code,
                    Status = request.Status.Value,
                    Remark = request.Remark,
                    DisplayOrder = int.Parse(request.DisplayOrder),
                    CreatedBy = request.CreatedBy,
                    CreateTime = DateTime.Now
                };

                //新增
                var resultId = _db.DbConnection.Insert<Containers>(container);
                if (resultId <= 0)
                {
                    throw new Exception("新增容器失败.");
                }
                response.Success = true;
            }
            return response;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<ContainerQueryResponse> GetPager(ContainerQuery query)
        {
            var pageIndex = query.PageIndex <= 0 ? 0 : (query.PageIndex - 1) * query.PageSize;

            var files = "Id,Type,Code,Locked,Status,Remark,DisplayOrder,CreatedBy,CreateTime";
            var tableName = "t_containers";
            var orderby = "ORDER BY Id ASC";
            var where = "where 1=1";

            #region 条件
            //if (!string.IsNullOrEmpty(query.Name))
            //{
            //    where += string.Format(" And Name like'%{0}%'", query.Name);
            //}
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            //sb.AppendFormat("select {0} from {1} {2} {3} offset {4} rows fetch next {5} rows only", files, tableName, where, orderby, pageIndex, query.PageSize);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, pageIndex, query.PageSize);
            using (var multi = _db.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<ContainerQueryResponse>();

                return new DataGrid<ContainerQueryResponse>()
                {
                    Rows = list,
                    Total = count
                };
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public DataGrid<ContainerQueryResponse> ContainerQuery(ContainerQuery query)
        {
            var pageIndex = query.PageIndex <= 0 ? 0 : (query.PageIndex - 1) * query.PageSize;

            var files = "Id,Code,Locked,Status,Remark,DisplayOrder,CreatedBy,CreateTime";
            var tableName = "t_containers";
            var orderby = "ORDER BY Id ASC";
            var where = "where Code NOT IN(SELECT ContainerCode FROM t_warehouseunit WHERE ContainerCode IS NOT NULL)";

            #region 条件
            if(query.Locked.HasValue)
            {
                where += string.Format(" And Locked ={0}", query.Locked.Value);
            }
            //if (!string.IsNullOrEmpty(query.Name))
            //{
            //    where += string.Format(" And Name like'%{0}%'", query.Name);
            //}
            #endregion

            var sb = new StringBuilder();

            sb.AppendFormat("SELECT COUNT(1) FROM {0} {1};", tableName, where);
            //sb.AppendFormat("select {0} from {1} {2} {3} offset {4} rows fetch next {5} rows only", files, tableName, where, orderby, pageIndex, query.PageSize);
            sb.AppendFormat("SELECT {0} FROM {1} {2} {3} LIMIT {4},{5};", files, tableName, where, orderby, pageIndex, query.PageSize);
            using (var multi = _db.DbConnection.QueryMultiple(sb.ToString()))
            {
                var count = multi.ReadFirst<int>();

                var list = multi.Read<ContainerQueryResponse>();

                return new DataGrid<ContainerQueryResponse>()
                {
                    Rows = list,
                    Total = count
                };
            }
        }
    }
}
